package com.crcloud.auth.config;

import check.CheckUtils;
import com.crcloud.auth.domain.ClientConfig;
import com.netflix.discovery.converters.Auto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.password.Pbkdf2PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.builders.ClientDetailsServiceBuilder;
import org.springframework.security.oauth2.config.annotation.builders.InMemoryClientDetailsServiceBuilder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;

// 配置授权服务器
@Configuration
@EnableAuthorizationServer
public class MyAuthorizationServer extends AuthorizationServerConfigurerAdapter {
    private static final int TOKEN_VALIDITY_SECOND = 1800; // half hour

    @Autowired
    AllClientConfigs clientConfigs;

    // 认证管理器
    @Autowired
    @Qualifier("authenticationManagerBean")
    AuthenticationManager authenticationManager;

    @Autowired
    ClientDetailsService clientDetailsService;

    @Bean
    TokenStore tokenStore() {
        return new InMemoryTokenStore();
    }

    @Bean
    AuthorizationServerTokenServices tokenServices() {
        DefaultTokenServices services = new DefaultTokenServices();
        services.setClientDetailsService(clientDetailsService);
        services.setSupportRefreshToken(true);
        services.setTokenStore(tokenStore());
        services.setAccessTokenValiditySeconds(TOKEN_VALIDITY_SECOND);
        services.setRefreshTokenValiditySeconds(60 * 60 * 24 * 3);
        return services;
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return new Pbkdf2PasswordEncoder();
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.tokenKeyAccess("permitAll()").checkTokenAccess("permitAll()").allowFormAuthenticationForClients();
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        if (CheckUtils.isEmpty(clientConfigs.getList())) {
            return;
        }
        InMemoryClientDetailsServiceBuilder inMemory = clients.inMemory();
        for (ClientConfig client : clientConfigs.getList()) {
            ClientDetailsServiceBuilder<InMemoryClientDetailsServiceBuilder>.ClientBuilder clientBuilder =
                    inMemory.withClient(client.getClientId());

            if (CheckUtils.isNotEmpty(client.getSecret())) {
                clientBuilder.secret(client.getSecret());
            }

            clientBuilder.authorizedGrantTypes(client.getGrantType().split(","));
            clientBuilder.scopes(client.getScopes().split(","));

            if ("ui".equalsIgnoreCase(client.getScopes())) {
                clientBuilder.accessTokenValiditySeconds(TOKEN_VALIDITY_SECOND);
            }

            if ("server".equalsIgnoreCase(client.getScopes())) {
                clientBuilder.authorities(new String[]{"ROLE_USER"});
            }
        }

        /*clients.inMemory()
                .withClient("account-service")
                .secret(passwordEncoder().encode("123"))
                .authorizedGrantTypes("client_credentials", "refresh_token") // 客户端模式
                .scopes("server")
                .and()
                .withClient("codehook-service")
                .secret(passwordEncoder().encode("123"))
                .resourceIds("codehook-service")
                .authorizedGrantTypes("client_credentials", "refresh_token") // 客户端模式
                .scopes("server")
                .and()
                .withClient("configuration-service")
                .secret(passwordEncoder().encode("123"))
                .resourceIds("configuration-service")
                .authorizedGrantTypes("client_credentials", "refresh_token") // 客户端模式
                .scopes("server")
                .and()
                .withClient("middleware-service")
                .secret(passwordEncoder().encode("123"))
                .resourceIds("middleware-service")
                .authorizedGrantTypes("client_credentials", "refresh_token") // 客户端模式
                .scopes("server")
                .and()
                .withClient("publishment-service")
                .secret(passwordEncoder().encode("123"))
                .resourceIds("publishment-service")
                .authorizedGrantTypes("client_credentials", "refresh_token") // 客户端模式
                .scopes("server")
                .and()
                .withClient("browser")
                .authorizedGrantTypes("password", "refresh_token") // 密码模式
                .scopes("ui");*/
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager)
                .tokenServices(tokenServices());
    }
}
